﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using com.km.Cache;
using com.km.library;
using Activity;
using Activity.Helper;

// ReSharper disable once CheckNamespace
namespace com.km {
	/// <summary>
	/// 维护在线用户列表
	/// </summary>
	public static class OnlineUsers {
		const string CACHE_KEY = "online-users:";
		const string CACHE_KEY_OPENID = CACHE_KEY + "openid:";
        const string CACHE_KEY_CUSID = CACHE_KEY + "cusid:";
        static void AddUser(OnlineUser user) {
			if (HttpContext.Current == null || HttpContext.Current.Session == null) return;
            //RedisCache.AddObject(CACHE_KEY_CUSID + user.CusID, user, HttpContext.Current.Session.Timeout);
            RedisCache.MinString(CACHE_KEY_CUSID + user.CusID,user.ToJson(), HttpContext.Current.Session.Timeout);
		}

		static void RemoveUser(OnlineUser user) {
			RedisCache.Remove(CACHE_KEY_CUSID + user.CusID);
		}
		static void RemoveUser(string openId) {
		    if (RedisCache.Exists("openid2userid:" + openId)){
		        var cusId = (int) RedisCache.Get("openid2userid:" + openId);
                RedisCache.Remove("openid2userid:" + openId);
                RemoveUser(cusId);
		    }
            RedisCache.Remove(CACHE_KEY_OPENID + openId);
        }
        static void RemoveUser(int cusId) {
            if (RedisCache.Exists("userid2openid:" + cusId)){
                var openid = (string) RedisCache.Get("userid2openid:" + cusId);
                RedisCache.Remove("userid2openid:" + cusId);
                RemoveUser(openid);
            }
            RedisCache.Remove(CACHE_KEY_CUSID + cusId);
        }
        public static string GetToken() {
			var guid = Guid.NewGuid();
			//RedisCache.Add(guid.ToString(), UserInfo.OpenID, 30);
            RedisCache.Add(guid.ToString(), UserInfo.CusIDInt, 30);
            return guid.ToString();
		}

		public static string GetAnonymousToken(string Name){
			var guid = Guid.NewGuid();
			RedisCache.Add("N:"+guid.ToString(), Name, 3000);
			return "N:" + guid.ToString();
		}

		/// <summary>
		/// 把当前用户添加到在线用户列表
		/// </summary>
		public static void AddAndRefresh(OnlineUser user) {
			AddUser(user);
		}
        /// <summary>
        /// 检查用户在线
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public static bool CheckUserOnline(string UserID)
        {
            var key = CACHE_KEY_CUSID + UserID;
            var exists = RedisCache.Exists(key);
            return exists;
        }
		/// <summary>
		/// 移除在线用户信息
		/// </summary>
		public static void Remove() {
			if (Count < 1) {
				return;
			}
			RemoveUser(UserInfo.CusIDInt);
		}
		/// <summary>
		/// 在线用户数量
		/// </summary>
		public static long Count => RedisCache.Count(CACHE_KEY_CUSID + "*");

	    /// <summary>
		/// 获取在线用户列表（最近有刷新的排前）
		/// </summary>
		/// <param name="count"></param>
		/// <returns></returns>
		public static List<OnlineUser> GetUsers(int count = 100) {
			var keys = RedisCache.GetKeys(CACHE_KEY_CUSID + "*", count);
            List<OnlineUser> list = new List<OnlineUser>();
            foreach(var key in keys)
            {
                var item = RedisCache.GetAndDecodeJson<OnlineUser>(key);
                list.Add(item);
            }
            return list;
        }
	}
	[Serializable]
	public class OnlineUser {
        public int CusID { get; set; }
        public string UserCode { get; set; }
		public string UserName { get; set; }
		public DateTime LoginDate { get; set; }
		public DateTime RefreshTime { get; set; }
        public string Browser { get; set; }
        public string OSName { get; set; }
        public string IPAddress { get; set; }
		/// <summary>
		/// 用户VIP等级
		/// </summary>
		public int CusType { get; set; }
		public string OnlineTime {
			get {
				var st = DateTime.Now - this.LoginDate;
				return st.Hours > 0
					? $"{st.Hours:D}小时{st.Minutes:D}分{st.Seconds:D}秒"
				    : (st.Minutes > 0
						? $"{st.Minutes:D}分{st.Seconds:D}秒"
				        : $"{st.Seconds:D}秒");
			}
		}
	}
}
